/** 
 * Project Name:kaka 
 * File Name:PersonalCardAction.java 
 * Package Name:com.luoran.kaka.api.wechat 
 * Date:2018年12月10日下午2:30:14 
 * Copyright (c) 2018, Luoran, Inc. All Rights Reserved.
 * 
 */
package com.luoran.kaka.api.wechat;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.luoran.kaka.entity.BasicInfo;
import com.luoran.kaka.entity.PicInfo;
import com.luoran.kaka.service.IAboutInfoService;
import com.luoran.kaka.service.IBasicInfoService;
import com.luoran.kaka.service.IPicInfoService;
import com.luoran.kaka.utils.UUID;

/** 
 * @author ghl 
 * @since JDK 1.8
 * ClassName: PersonalCardAction
 * date: 2018年12月10日 下午2:30:14
 *	
 */
@Controller
@RequestMapping("/api/personal")
public class PersonalCardAction {

	private static final Logger log = LoggerFactory.getLogger(PersonalCardAction.class);

	@Autowired
	private Environment evn;
	@Autowired
	private IPicInfoService picInfoService;
	@Autowired
	private IBasicInfoService basicInfoService;
	@Autowired
	private IAboutInfoService aboutInfoService;


	/** 
	 * 
	 * @author ghl 2018年12月10日下午8:02:15
	 * @param req
	 * @return 
	 * @since JDK 1.8
	 * doUpload:新建简易卡片个人图片上传
	 */
	@RequestMapping("/card/upload")
	@ResponseBody
	public JSONObject doUpload(HttpServletRequest req) {
		JSONObject obj = new JSONObject();
		PicInfo pic = new PicInfo();
		MultipartHttpServletRequest multiparReq = (MultipartHttpServletRequest) req;
		Iterator<String> fileNames = multiparReq.getFileNames();
		if (fileNames.hasNext()) {
			try {
				MultipartFile file = multiparReq.getFile(fileNames.next());
				String originalName = file.getOriginalFilename();
				long size = file.getSize();
				String suffix = originalName.substring(originalName.lastIndexOf(".")).toLowerCase();// 原始后缀小写
				String path = evn.getProperty("file.path");// 获取图片存储目录
				String newFileName = UUID.get() + suffix;// 根据UUID生成新的文件名称带后缀
				String depositUrl = path + "/" + newFileName;
				File dest = new File(depositUrl);// 上传目标路径
				if (!dest.getParentFile().exists()) {
					dest.getParentFile().mkdirs();
					log.info("父及目录不存在，创建父及目录。");
				}
				file.transferTo(dest);// 图片上传
				pic.setOriginalName(originalName);
				pic.setSize((int) size);
				pic.setName(newFileName);
				pic.setDepositUrl(depositUrl);
				pic.setUrl(evn.getProperty("file.path.url") + req.getContextPath() + "/" + newFileName);// 根据配置的虚拟路径可以直接用url访问本地图片,正式上线可以通过nginx反向代理访问linux图片目录
				pic.setCreatetime(new Date());
				pic.setLastupdatetime(new Date());
				String picId = picInfoService.insertPic(pic);
				if (!StringUtils.isEmpty(picId)) {
					String url = pic.getUrl();
					log.info("图片上传成功,访问地址为{{}}",url);
					obj.put("flag", true);
					obj.put("url", url);
					obj.put("picId", picId);
				}
			} catch (Exception e) {
				e.printStackTrace();
				obj.put("flag", false);
				obj.put("msg", "网络异常");
			}
		}
		return obj;
	}


	/** 
	 * 
	 * @author ghl 2018年12月10日下午8:01:45
	 * @param info
	 * @return 
	 * @since JDK 1.8
	 * saveSimplePersonalCard:保存简易个人名片
	 */
	@RequestMapping("/card/save")
	@ResponseBody
	public JSONObject saveSimplePersonalCard(BasicInfo info) {
		log.info("保存个人名片基本信息");
		JSONObject obj = new JSONObject();
		if (info != null) {
			if (StringUtils.isEmpty(info.getUserName())) {
				obj.put("flag", false);
				obj.put("msg", "姓名不能为空");
				return obj;
			}
		}
		try {
			info.setCreatetime(new Date());
			info.setLastupdatetime(new Date());
			String id = basicInfoService.add(info);
			if (StringUtils.isEmpty(id)) {
				obj.put("flag", false);
				obj.put("msg", "网络异常");
			} else {
				obj.put("flag", true);
				obj.put("cardId", id);
				obj.put("msg", "保存成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("flag", false);
			obj.put("msg", "网络异常");
		}
		return obj;
	}


	/** 
	 * 
	 * @author ghl 2018年12月11日下午3:15:03
	 * @param id
	 * @return 
	 * @since JDK 1.8
	 * personalCardView:查看个人名片
	 */
	@RequestMapping("/view/{id}")
	@ResponseBody
	public JSONObject personalCardView(@PathVariable("id") String id) {
		log.info("参数个人名片ID为{{}}", id);
		JSONObject obj = new JSONObject();
		BasicInfo basicInfo = basicInfoService.getBasicInfoById(id);
		if (basicInfo != null) {
			obj.put("flag", true);
			obj.put("info", basicInfo);
			if (!StringUtils.isEmpty(basicInfo.getPicId())) {
				PicInfo picInfo = picInfoService.getPicInfoById(basicInfo.getPicId());
				if (null != picInfo) {
					obj.put("picUrl", picInfo.getUrl());
				}
			}
		} else {
			obj.put("flag", false);
			obj.put("msg", "该记录已不存在");
		}
		return obj;
	}
	
	
	/** 
	 * 
	 * @author ghl 2018年12月12日上午10:59:15
	 * @param basicInfo
	 * @return 
	 * @since JDK 1.8
	 * saveMoreInfo:添加更多信息
	 */ 
	@RequestMapping("/card/save/more")
	@ResponseBody
	public JSONObject saveMoreInfo(BasicInfo info) {
		log.info("保存个人名片基本信息");
		JSONObject obj = new JSONObject();
		if (info != null) {
			if (StringUtils.isEmpty(info.getUserName())) {
				obj.put("flag", false);
				obj.put("msg", "姓名不能为空");
				return obj;
			}
		}
		try {
			info.setCreatetime(new Date());
			info.setLastupdatetime(new Date());
			String id = basicInfoService.add(info);
			if (StringUtils.isEmpty(id)) {
				obj.put("flag", false);
				obj.put("msg", "网络异常");
			} else {
				obj.put("flag", true);
				obj.put("cardId", id);
				obj.put("msg", "保存成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			obj.put("flag", false);
			obj.put("msg", "网络异常");
		}
		return obj;
	}

	/**
	 * 
	 * findOne: 根据id查询个人信息及风采
	 */
	@RequestMapping("/oneById")
	@ResponseBody
	public JSONObject findOne(HttpServletRequest resquest) {
		JSONObject obj=new JSONObject();
		String id=resquest.getParameter("id");
		if(!StringUtils.isEmpty(id)) {
			List<Object> aboutList = aboutInfoService.getAboutInfosById(id);
			BasicInfo basic=basicInfoService.getBasicInfoById(id);
			obj.put("basic", basic);
			obj.put("aboutList", aboutList);
			obj.put("flag", true);
		}else {
			obj.put("flag", false);
		}
		return obj;
	}
	
	
	@RequestMapping("/card/update")
	@ResponseBody
	public JSONObject update(BasicInfo basic) {
		JSONObject obj=new JSONObject();
		int result = basicInfoService.updateUserInfo(basic);
		if(result>0) {
			obj.put("flag", true);
			obj.put("wxOpenId", basic.getWxOpenId());
		}else {
			obj.put("flag", false);
		}
		return obj;
	}
}
